package mi.payment.db;

import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.query.DeleteQuery;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

import mi.payment.constants.Configs;
import mi.payment.db.dao.DBManager;
import mi.payment.db.dao.DaoMaster;
import mi.payment.db.dao.DaoSession;
import mi.payment.db.dao.UserInfo;
import mi.payment.db.dao.UserInfoDao;

/**
 * 用户管理类
 */
public class UserInfoModel {

    private UserInfoDao userInfoDao;

    private static UserInfoModel instance;

    private UserInfoModel() {
        SQLiteDatabase database = DBManager.getInstance().getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(database);
        DaoSession daoSession = daoMaster.newSession(IdentityScopeType.None);
        userInfoDao = daoSession.getUserInfoDao();
    }

    public static UserInfoModel getInstance() {
        if (instance == null) {
            instance = new UserInfoModel();
        }
        return instance;
    }

    /**
     * 初始化默认用户
     * 一般操作员：1
     * 管理操作员：2
     * 系统管理员：3
     * 01-05，五个一般操作员，初始密码：0000
     * 管理操作员，操作代码为：00，初始密码：123456
     * 系统管理员操作代码为：99 初始密码为88888888
     */
    public void initTable() {
        List<String> list = queryAllUserId();
        if (list != null && list.size() == 0) {
            List<UserInfo> userList = new ArrayList<>();
            // 一般操作员
            UserInfo userInfo1 = new UserInfo("01", 1, "0000");
            UserInfo userInfo2 = new UserInfo("02", 1, "0000");
            UserInfo userInfo3 = new UserInfo("03", 1, "0000");
            UserInfo userInfo4 = new UserInfo("04", 1, "0000");
            UserInfo userInfo5 = new UserInfo("05", 1, "0000");
            userList.add(userInfo1);
            userList.add(userInfo2);
            userList.add(userInfo3);
            userList.add(userInfo4);
            userList.add(userInfo5);
            // 管理操作员
            UserInfo managerUI = new UserInfo("00", 2, "123456");
            userList.add(managerUI);
            // 系统管理员
            UserInfo systemUI = new UserInfo("99", 3, Configs.defaultAdminPassword);
            userList.add(systemUI);
            // 插入
            for (UserInfo userInfo : userList) {
                generateUser(userInfo);
            }
        }
    }

    /**
     * 用户登陆
     */
    public UserInfo login(String uid, String pwd) {
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        qb.where(
                UserInfoDao.Properties.UId.eq(uid),
                UserInfoDao.Properties.UPwd.eq(pwd)
        );
        return qb.build().unique();
    }

    /**
     * 根据规则生成UID
     */
    public String generateUId() {
        List<String> list = queryAllUserId();
        for (int i = 1; i <= 98; i++) {
            String uId = "";
            if (i <= 9) {
                uId = "0" + i;
            } else {
                uId = "" + i;
            }
            boolean contains = list == null || list.contains(uId);
            if (contains) continue;
            return uId;
        }
        return "";
    }

    /**
     * 指定用户Id添加密码
     */
    private void generateUser(UserInfo userInfo) {
        String uId = userInfo.getUId();
        // 插入前判断该user是否已在数据库中
        if (queryUserInfoById(uId) != null) {
            return;
        }
        userInfoDao.insert(userInfo);
    }

    /**
     * 添加一个用户
     * type返回类型
     * 1：添加成功
     * 2：无法生成ID
     * 3：用户数量大于23
     */
    public int addNewUser(String uPwd) {
        // 操作列表不能超过21个和1个用户管理员和1个系统管理员一共23
        List<String> list = queryAllUserId();
        if (list != null && list.size() > 23) return 3;
        // 生成用户ID
        String uId = generateUId();
        if (uId == null || uId.trim().length() == 0) return 2;
        UserInfo userInfo = new UserInfo();
        userInfo.setUId(uId);
        userInfo.setUPwd(uPwd);
        userInfo.setUType(1);
        generateUser(userInfo);
        return 1;
    }

    /**
     * 根据用户ID删除用户
     */
    public void deleteUserById(String uId) {
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        DeleteQuery<UserInfo> dq = qb.where(
                UserInfoDao.Properties.UId.eq(uId)
        ).buildDelete();
        dq.executeDeleteWithoutDetachingEntities();
    }

    /**
     * 修改用户密码
     */
    public UserInfo modifyUserPwd(String uId, String oldPwd, String newPwd) {
        // 验证旧密码
        UserInfo info = login(uId, oldPwd);
        if (info == null) {
            return null;
        }
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        qb.where(UserInfoDao.Properties.UId.eq(uId));
        UserInfo userInfo = qb.build().unique();
        if (userInfo != null) {
            userInfo.setUPwd(newPwd);
            // 更新密码
            userInfoDao.update(userInfo);
            info = login(uId, newPwd);
            return info;
        }
        return null;
    }

    /**
     * 获取用户列表
     */
    public List<UserInfo> queryAllUser() {
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        return qb.list();
    }

    /**
     * 根据用户UID查询UserInfo
     */
    public UserInfo queryUserInfoById(String uid) {
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        qb.where(
                UserInfoDao.Properties.UId.eq(uid)
        );
        return qb.build().unique();
    }

    /**
     * 获取用户UID列表
     */
    public List<String> queryAllUserId() {
        List<String> list = new ArrayList<>();
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        List<UserInfo> infoList = qb.list();
        if (infoList != null && infoList.size() > 0) {
            for (UserInfo userInfo : infoList) {
                String uId = userInfo.getUId();
                list.add(uId);
            }
        }
        return list;
    }


}
